import {addUser, queryUserList, removeUser, updateUser, updateUserRoleList} from '@/pages/system/UserList/service';
import {DeleteOutlined, EditOutlined, ExclamationCircleOutlined, PlusOutlined, SettingOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns, ProDescriptionsItemProps} from '@ant-design/pro-components';
import {FooterToolbar, PageContainer, ProDescriptions, ProTable,} from '@ant-design/pro-components';
import {Button, Divider, Drawer, message, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import type {updateUserRoleParams, UserListItem} from "@/pages/system/UserList/data";
import CreateUserForm from "@/pages/system/UserList/components/CreateUserForm";
import UpdateUserForm from "@/pages/system/UserList/components/UpdateUserForm";
import SetUserRoleForm from "@/pages/system/UserList/components/SetUserRoleForm";

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: UserListItem) => {
  const hide = message.loading('正在添加');
  try {
    await addUser({...fields});
    hide();
    message.success('添加成功,即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试!');
    return false;
  }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: UserListItem) => {
  const hide = message.loading('正在更新');
  try {
    await updateUser({...fields});
    hide();
    message.success('更新成功,即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试!');
    return false;
  }
};

/**
 * @en-US Update user role
 * @zh-CN 更新用户角色
 *
 * @param fields
 */
const handleUserRole = async (fields: updateUserRoleParams) => {
  const hide = message.loading('正在更新');
  try {
    await updateUserRoleList({...fields});
    hide();
    message.success('更新成功,即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试!');
    return false;
  }
};

/**
 * @en-US Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: UserListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeUser(
      selectedRows.map((row) => row.id),
    );
    hide();
    message.success('删除成功,即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试!');
    return false;
  }
};

const UserList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [roleModalVisible, handleRoleModalVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<UserListItem>();
  const [selectedRowsState, setSelectedRows] = useState<UserListItem[]>([]);

  const showDeleteConfirm = (item: UserListItem) => {
    Modal.confirm({
      title: '是否删除记录?',
      icon: <ExclamationCircleOutlined/>,
      content: '删除的记录不能恢复,请确认!',
      onOk() {
        handleRemove([item]).then(() => {
          actionRef.current?.reloadAndRest?.();
        });
      },
      onCancel() {
      },
    });
  };

  const columns: ProColumns<UserListItem>[] = [
    {
      title: "id",
      dataIndex: 'id',
      hideInSearch: true,
    },
    {
      title: "用户名",
      dataIndex: 'userName',
      render: (dom, entity) => {
        return <a onClick={() => {
          setCurrentRow(entity)
          setShowDetail(true)
        }
        }>{dom}</a>;
      },
    },
    {
      title: "手机号",
      dataIndex: 'mobile',
      render: (dom, entity) => {
        return <a onClick={() => {
          setCurrentRow(entity)
          setShowDetail(true)
        }
        }>{dom}</a>;
      },
    },
    {
      title: "状态",
      dataIndex: 'statusId',
      valueEnum: {
        0: {text: '禁用', status: 'Error'},
        1: {text: '正常', status: 'Success'},
      },
    },
    {
      title: "排序",
      dataIndex: 'sort',
      hideInSearch: true,
    },
    {
      title: "备注",
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: "创建时间",
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: "更新时间",
      dataIndex: 'updateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 400,
      render: (_, record) => (
        <>
          <Button
            type="primary"
            // disabled={!hasPm("/api/system/user/view")}
            onClick={() => {
              handleUpdateModalVisible(true);
              setCurrentRow(record);
            }}
          >
            <EditOutlined/>编辑
          </Button>
          <Divider type="vertical"/>
          <Button
            type="default"
            // disabled={!hasPm("/api/system/role/userRoleSave")}
            onClick={() => {
              handleRoleModalVisible(true);
              setCurrentRow(record);
            }}
            style={{backgroundColor: '#626aef', color: 'white'}}
            icon={<SettingOutlined/>}
          >
            设置角色
          </Button>
          <Divider type="vertical"/>
          <Button
            type="primary"
            danger
            // disabled={!hasPm("/api/system/user/delete")}
            onClick={() => {
              showDeleteConfirm(record);
            }}
          >
            <DeleteOutlined/>删除
          </Button>
        </>
      ),
    },
  ];

  return (
    <PageContainer header={{title: ""}}>
      <ProTable<UserListItem, API.PageParams>
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined/> 新建用户
          </Button>,
        ]}
        request={queryUserList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        pagination={{pageSize: 10}}
      />

      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{fontWeight: 600}}>{selectedRowsState.length}</a> 项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            type={"primary"}
            danger
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <DeleteOutlined/>批量删除
          </Button>
        </FooterToolbar>
      )}

      <CreateUserForm
        onCreate={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          setCurrentRow(undefined);

        }}
        open={createModalVisible}
      />

      <UpdateUserForm
        onCreate={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        open={updateModalVisible}
        item={currentRow}
      />

      <SetUserRoleForm
        onCreate={async (value) => {
          const success = await handleUserRole(value);
          if (success) {
            handleRoleModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleRoleModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        open={roleModalVisible}
        item={currentRow}
      />

      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<UserListItem>
            column={2}
            title={currentRow?.userName}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<UserListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default UserList;
